const Moment = require('moment')
const express = require('express')
const router = express.Router()
const path = require('path')

const bodyParser = require('body-parser')
const expressValidator = require('express-validator')
const check = expressValidator.check
const validationResult = expressValidator.validationResult

const db = require('../db/db').db

// 创建application/x-www-form-urlencoded
router.use(bodyParser.urlencoded({
    extended: true
}))
// 创建application/json解析
router.use(bodyParser.json())

// 列表
router.get('/', (req, res, next) => {
    let sqlStr = 'SELECT * FROM tasktype;'
    let connection = db.connection()
    db.query(connection, sqlStr, (err, result) => {
        try {
            res.render(path.join(path.dirname(__dirname), 'views', 'tasktypelist', 'index'), {
                title: '所有任务类型',
                list: result.map((item) => {
                    return Object.assign({}, item, {
                        createtime: Moment(item.createtime).format('YYYY-MM-DD HH:mm:ss')
                    })
                })
            })
        } catch (err) {}
    })
})

// 添加
router.get('/add', (req, res) => {
    res.render(path.join(path.dirname(__dirname), 'views', 'tasktypeadd', 'index'), {
        title: '添加任务类型'
    })
})

// 添加
router.post('/add', [
    check('name')
        .not()
        .isEmpty()
        .withMessage('请输入任务类型名称')
], (req, res) => {
    let errors = validationResult(req)
    if (!errors.isEmpty()) {
        return res.render(path.join(path.dirname(__dirname), 'views', 'tasktypeadd', 'index'), {
            title: '添加任务类型',
            err: Object.values(errors.mapped())[0].msg
        })
    }
    let tasktype = {
        name: req.body.name,
        createtime: Moment().format('YYYY-MM-DD HH:mm:ss')
    }
    // 防止插入重复数据
    let sqlStr = `
        INSERT INTO tasktype(name, createtime)
        SELECT '${tasktype.name}', '${tasktype.createtime}'
        FROM DUAL
        WHERE NOT EXISTS(SELECT name FROM tasktype WHERE name = '${tasktype.name}')
    `
    
    let connection = db.connection()
    db.query(connection, sqlStr, tasktype, (id) => {
        setTimeout(() => {
            res.redirect('/tasktype/')
        }, 0)
    })
    db.close(connection)
    return false
})

// 删除
router.get('/delete', (req, res) => {
    let sqlStr = `
        DELETE FROM tasktype WHERE id = '${req.query.typeId}'
    `
    let connection = db.connection()
    db.query(connection, sqlStr, () => {
        setTimeout(() => {
            res.redirect('/tasktype')
        }, 0)
    })
    db.close(connection)
    return false
})

module.exports = router